package com.example.shardingsphere.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory;
import io.shardingjdbc.core.api.config.MasterSlaveRuleConfiguration;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author haitao.li
 * @description: 数据源配置
 * @date 2021/4/28 17:34
 */
@Configuration
public class ShardingSphereDataSource {

    /**
     * 订单
     */
    @Bean(name = "orderDataSource")
    @ConfigurationProperties(prefix = "shardingsphere.order.datasource")
    public DataSource orderDataSource() {
        return new DruidDataSource();
    }

    /**
     * 库存
     */
    @Bean(name = "stockDataSource")
    @ConfigurationProperties(prefix = "shardingsphere.stock.datasource")
    public DataSource stockDataSource() {
        return new DruidDataSource();
    }


    /**
     * 配置订单和库存数据源路由
     *
     * @param orderDataSource 订单
     * @param stockDataSource 库存
     * @return
     */
    @Bean(name = "shardingDataSource")
    public DataSource shardingDataSource(@Qualifier("orderDataSource") DataSource orderDataSource,
                                         @Qualifier("stockDataSource") DataSource stockDataSource) throws SQLException {
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("orderDataSource", orderDataSource);
        dataSourceMap.put("stockDataSource", stockDataSource);


        // 构建读写分离配置
        MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration();
        masterSlaveRuleConfig.setName("ms_ds");
        masterSlaveRuleConfig.setMasterDataSourceName("orderDataSource");
        masterSlaveRuleConfig.getSlaveDataSourceNames().add("stockDataSource");

        final DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, masterSlaveRuleConfig, new HashMap<>());
        return dataSource;

    }
}
